
#include "WxClient.hpp"
#include <arpa/inet.h>
#include <cstdio>
#include <cstdlib>
#include "Logger.hpp"
#include "RenameDialog.hpp"
#include "AddDirDialog.hpp"

#include <algorithm>    // std::sort
#include <errno.h>
#include <pwd.h>

#include <fstream>

IMPLEMENT_APP(MainApp)
/*
 * On initialization of the application the mainframe is build and shown.
 */
bool MainApp::OnInit() {
    MainFrame *frame = new MainFrame(_("Client"), wxPoint(50, 50), wxSize(750, 500));
    //frame->SetExtraStyle(wxTAB_TRAVERSAL);
    frame->Centre();
    frame->Show(true);
    SetTopWindow(frame);
    return true;
}

/*
 * All the events are linked in this table.
 * Every buttons are linked to an ID and the ID to a method.
 */
BEGIN_EVENT_TABLE(MainFrame, wxFrame)
EVT_BUTTON(ID_Logon, MainFrame::logon)
EVT_BUTTON(ID_Quit, MainFrame::cancel)
EVT_BUTTON(ID_Upload, MainFrame::upload)
EVT_BUTTON(ID_Download, MainFrame::download)
EVT_BUTTON(ID_Refresh, MainFrame::refresh)
EVT_BUTTON(ID_DeleteClient, MainFrame::deleteClient)
EVT_BUTTON(ID_RenameClient, MainFrame::renameClient)
EVT_BUTTON(ID_DeleteServer, MainFrame::deleteServer)
EVT_BUTTON(ID_RenameServer, MainFrame::renameServer)
EVT_BUTTON(ID_AddDirClient, MainFrame::addDirClient)
EVT_BUTTON(ID_AddDirServer, MainFrame::addDirServer)
END_EVENT_TABLE()

/*
 * Constructor of the Mainframe, initialization of variables.
 * First screen (connectScreen) is created.
 */
MainFrame::MainFrame(const wxString &title, const wxPoint &pos, const wxSize &size) : wxFrame(NULL, -1, title, pos, size) {
    con = Connection();
    rCode = 0;
    screenSize = size;
    cc = ClientCommands();
    createConnectScreen();
}

/*
 * this method makes all the necessary buttons and text fields to connect and login the client to the server.
 */
void MainFrame::createConnectScreen() {
    std::vector<std::string> conf;
    std::ifstream myfile("Configfile");
    if (myfile.is_open()) {
        std::string line;
        for (int i = 0; i < 3; i++) {
            getline(myfile, line);
            conf.push_back(line);
        }
        myfile.close();
    } else {
        Logger::getInstance().log("Configfile cannot be read");
        for (int i = 0; i < 3; i++) {
            conf.push_back("");
        }
    }
    ;
    wxString portconf(conf.at(1).c_str(), wxConvUTF8);
    wxString userconf(conf.at(2).c_str(), wxConvUTF8);
    IPPortText = new wxStaticText(this, wxID_ANY, wxT("IP/Port:"),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2 - 80, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT * 3),
            wxSize(100, DEFAULTTEXTBOXHEIGHT));
    ip = new wxTextCtrl(this, ID_Ip, wxString(conf.at(0).c_str(), wxConvUTF8),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT * 3),
            wxSize(DEFAULTTEXTBOXWIDTH - 50, DEFAULTTEXTBOXHEIGHT),
            0, wxDefaultValidator, wxTextCtrlNameStr);
    port = new wxTextCtrl(this, ID_Port, wxString(conf.at(1).c_str(), wxConvUTF8),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2 + 150, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT * 3),
            wxSize(DEFAULTTEXTBOXWIDTH - 150, DEFAULTTEXTBOXHEIGHT),
            0, wxDefaultValidator, wxTextCtrlNameStr);

    logonButton = new wxButton(this, ID_Logon, _T("Logon"),
            wxPoint((screenSize.x / 2 - DEFAULTBUTTONWIDTH), screenSize.y / 2),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    cancelButton = new wxButton(this, ID_Quit, _T("Cancel"),
            wxPoint(screenSize.x / 2, screenSize.y / 2),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);

    usernameText = new wxStaticText(this, wxID_ANY, wxT("Username:"),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2 - 80, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT * 2),
            wxSize(100, DEFAULTTEXTBOXHEIGHT));
    username = new wxTextCtrl(this, ID_UserName, wxString(conf.at(2).c_str(), wxConvUTF8),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT * 2),
            wxSize(DEFAULTTEXTBOXWIDTH, DEFAULTTEXTBOXHEIGHT),
            0, wxDefaultValidator, wxTextCtrlNameStr);

    passwordText = new wxStaticText(this, wxID_ANY, wxT("Password:"),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2 - 80, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT),
            wxSize(100, DEFAULTTEXTBOXHEIGHT));
    password = new wxTextCtrl(this, ID_Password, wxString("", wxConvUTF8),
            wxPoint(screenSize.x / 2 - DEFAULTTEXTBOXWIDTH / 2, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT),
            wxSize(DEFAULTTEXTBOXWIDTH, DEFAULTTEXTBOXHEIGHT),
            wxTE_PASSWORD, wxDefaultValidator, wxTextCtrlNameStr);

    saveLoginData = new wxCheckBox(this, ID_SaveLoginData, wxT("Remember login"),
                            wxPoint(screenSize.x / 2 + DEFAULTTEXTBOXWIDTH / 2 + 10, screenSize.y / 2 - DEFAULTTEXTBOXHEIGHT));
    saveLoginData->SetValue(true);

    if(conf.at(0).size() == 0) {
    	ip->SetFocus();
    } else {
    	password->SetFocus();
    }
}

/*
 * When the logon button is pressed this method will be called.
 * Here a connection will be made with the server with the given IP and port.
 * If making a connection was successful the client will try to login with the given username and password.
 * If successful all the textfields and buttons will be removed.
 */
void MainFrame::logon(wxCommandEvent& event) {
    int sd = -1;
    if (ip->GetValue().empty() || port->GetValue().empty() || username->GetValue().empty() || password->GetValue().empty()) {
        wxMessageBox(wxT("All fields must be filled in"));
    } else {
        if ((sd = con.createConnection(std::string(ip->GetValue().mbc_str()), std::string(port->GetValue().mbc_str()))) != -1) {
            cc.setSocketDescriptor(sd);
            if ((rCode = cc.requestLogon(std::string(username->GetValue().mbc_str()), std::string(password->GetValue().mbc_str()))) == 0) {
            	if (saveLoginData->GetValue()) {
            		writeConfig();
            	}
                ip->~wxTextCtrl();
                port->~wxTextCtrl();
                username->~wxTextCtrl();
                password->~wxTextCtrl();
                logonButton->~wxButton();
                cancelButton->~wxButton();
                IPPortText->~wxObject();
                usernameText->~wxObject();
                passwordText->~wxObject();
                createMainScreen();
            } else {
                errorBox(rCode);
                con.~Connection();
            }
        } else {
            wxMessageBox(wxT("Incorrect IP or Port number"));
        }
    }
}

/*
 * This method is called after the logon was successful.
 * Here the mainscreen will be made with the 2 directory lists and buttons.
 * A message will be send to the server to get the directorylist of the server.
 */
void MainFrame::createMainScreen() {
    //struct passwd *pw = getpwuid(getuid());
    //std::string homedir = pw->pw_dir;
    std::string homedir = get_current_dir_name();
    homedir += "/";

    currentClientDirectory = homedir;
    currentServerDirectory = "";

    uploadButton = new wxButton(this, ID_Upload, _T("Upload"),
            wxPoint(10, 50),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    uploadButton->Enable(cc.getHANIntern());
    deleteClientButton = new wxButton(this, ID_DeleteClient, _T("Delete"),
            wxPoint(10, 50 + DEFAULTBUTTONHEIGHT + 10),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    renameClientButton = new wxButton(this, ID_RenameClient, _T("Rename"),
            wxPoint(10, 50 + DEFAULTBUTTONHEIGHT * 2 + 10 * 2),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    addDirClientButton = new wxButton(this, ID_AddDirClient, _T("Add folder"),
            wxPoint(10, 50 + DEFAULTBUTTONHEIGHT * 3 + 10 * 3),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);

    refreshButton = new wxButton(this, ID_Refresh, _T("Refresh"),
            wxPoint(645, 50 - DEFAULTBUTTONHEIGHT - 10),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    downloadButton = new wxButton(this, ID_Download, _T("Download"),
            wxPoint(645, 50),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    deleteServerButton = new wxButton(this, ID_DeleteServer, _T("Delete"),
            wxPoint(645, 50 + DEFAULTBUTTONHEIGHT + 10),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    renameServerButton = new wxButton(this, ID_RenameServer, _T("Rename"),
            wxPoint(645, 50 + DEFAULTBUTTONHEIGHT * 2 + 10 * 2),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);
    addDirServerButton = new wxButton(this, ID_AddDirServer, _T("Add folder"),
            wxPoint(645, 50 + DEFAULTBUTTONHEIGHT * 3 + 10 * 3),
            wxSize(DEFAULTBUTTONWIDTH, DEFAULTBUTTONHEIGHT), 0);

    //TODO More spacing with names of files (list) and total path (static test)
    clientDir = wxString(currentClientDirectory.c_str(), wxConvUTF8);
    clientDirText = new wxStaticText(this, wxID_ANY, clientDir, wxPoint(120, 50), wxSize(150, DEFAULTTEXTBOXHEIGHT));
    clientList = new wxCheckListBox(this, ID_ClientList,
            wxPoint(120, 70),
            wxSize(250, 400));
    std::string tempstr = "/" + currentServerDirectory;
    serverDir = wxString(tempstr.c_str(), wxConvUTF8);
    serverDirText = new wxStaticText(this, wxID_ANY, serverDir, wxPoint(380, 50), wxSize(150, DEFAULTTEXTBOXHEIGHT));
    serverList = new wxCheckListBox(this, ID_ServerList,
            wxPoint(380, 70),
            wxSize(250, 400));

    getClientStruct(currentClientDirectory);
    getServerStruct();

    Connect(ID_ClientList, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(MainFrame::changeDirClient));
    Connect(ID_ServerList, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(MainFrame::changeDirServer));
}

//TODO set uploading bar (progress)

/*
 * When the upload button is pressed this method will be called.
 * It will upload all checked files to the server.
 */
void MainFrame::upload(wxCommandEvent& event) {
    if (getServerStruct() == 0) {
        for (unsigned int i = 0; i < clientList->GetCount(); i++) {
            wxString lItem = clientList->GetString(i);
            if (lItem.c_str()[lItem.size() - 1] != '/') {
                if (clientList->IsChecked(i)) {
                    if (!checkExists(std::string(lItem.mbc_str()), serverList)) {
                        std::string str = currentClientDirectory;
                        str += std::string(lItem.mbc_str());
                        if ((rCode = cc.requestUpload(str, currentServerDirectory)) != 0) {
                            errorBox(rCode);
                        }
                    } else {
                        wxMessageBox(wxT("File already exists"));
                    }
                }
            }
            clientList->Check(i, false);
        }
        getServerStruct();
    } else {
        wxMessageBox(wxT("Something went wrong when getting the directorystructure of the server."));
    }

}

//TODO set downloading bar (progress)

/*
 * When the download button is pressed this method will be called.
 * It will download all checked files to the client.
 */
void MainFrame::download(wxCommandEvent& event) {
    for (unsigned int i = 0; i < serverList->GetCount(); i++) {
        wxString lItem = serverList->GetString(i);
        if (lItem.c_str()[lItem.size() - 1] != '/') {
            if (serverList->IsChecked(i)) {
                if (!checkExists(std::string(lItem.mbc_str()), clientList)) {
                    std::string str = currentServerDirectory;
                    str += std::string(lItem.mbc_str());
                    if ((rCode = cc.requestDownload(str, currentClientDirectory)) != 0) {
                        errorBox(rCode);
                    }
                } else {
                    wxMessageBox(wxT("File already exists"));
                }
            }
        }
        serverList->Check(i, false);
    }
    getServerStruct();
    getClientStruct(currentClientDirectory);
}

/*
 * This method checks if the given filename already exists in the list.
 */
bool MainFrame::checkExists(std::string fileName, wxCheckListBox* list) {
    for (unsigned int i = 0; i < list->GetCount(); i++) {
        wxString lItem = list->GetString(i);
        if (strcmp(lItem.mbc_str(), fileName.c_str()) == 0) {
            return true;
        }
    }

    return false;
}

/*
 * refreshes the serverlist.
 */
void MainFrame::refresh(wxCommandEvent& event) {
    if (getServerStruct() == -1) {
        wxMessageBox(wxT("Something went wrong when getting the directorystructure of the server."));
    }
    getClientStruct(currentClientDirectory);
}

//TODO warning "are you sure?" yes/no dialog

/*
 * When the delete button at the server side is pressed this method will be called.
 * It will delete all checked files of the server.
 */
void MainFrame::deleteServer(wxCommandEvent& event) {
    int result = 0;

    for (unsigned int i = 0; i < serverList->GetCount(); i++) {
        wxString lItem = serverList->GetString(i);
        if (strcmp(lItem.mbc_str(), "../") != 0) {
            if (serverList->IsChecked(i)) {
                if (result == 0) {
                    wxMessageDialog *dial = new wxMessageDialog(NULL,
                            wxT("Are you sure you want to delete these files?"),
                            wxT("Delete"), wxYES_NO | wxNO_DEFAULT);
                    result = dial->ShowModal();
                }
                if (result == wxID_YES) {
                    std::string str = currentServerDirectory;
                    str += std::string(lItem.mbc_str());
                    if ((rCode = cc.requestDelete(str)) != 0) {
                        errorBox(rCode);
                    }
                }
            }
        }
        serverList->Check(i, false);
    }
    getServerStruct();
}

//TODO warning "are you sure?" yes/no dialog

/*
 * When the delete button at the client side is pressed this method will be called.
 * It will delete all checked files of the client.
 */
void MainFrame::deleteClient(wxCommandEvent& event) {
    int result = 0;
    for (unsigned int i = 0; i < clientList->GetCount(); i++) {
        wxString lItem = clientList->GetString(i);
        if (strcmp(lItem.mbc_str(), "../") != 0) {
            if (clientList->IsChecked(i)) {
                if (result == 0) {
                    wxMessageDialog *dial = new wxMessageDialog(NULL,
                            wxT("Are you sure you want to delete these files?"),
                            wxT("Delete"), wxYES_NO | wxNO_DEFAULT);
                    result = dial->ShowModal();
                }
                if (result == wxID_YES) {
                    std::string str = currentClientDirectory;
                    str += std::string(lItem.mbc_str());
                    if (remove(str.c_str()) != 0) {
                        errorBoxClient(errno);
                    }
                }

            }
        }
        clientList->Check(i, false);
    }
    getClientStruct(currentClientDirectory);
}

/*
 * When the rename button at the server side is pressed this method will be called.
 * It will create a rename popup to rename the selected file or directory on the server.
 */
void MainFrame::renameServer(wxCommandEvent& event) {
    int sel = serverList->GetSelection();
    if (sel != -1) {
        if (strcmp(serverList->GetString(sel).mbc_str(), "../") != 0) {
            new RenameDialog(wxT("Rename"), std::string(serverList->GetString(sel).mbc_str()), currentServerDirectory, cc, this);
            getServerStruct();
        }
    }
}

/*
 * When the rename button at the client side is pressed this method will be called.
 * It will create a rename popup to rename the selected file or directory on the client.
 */
void MainFrame::renameClient(wxCommandEvent& event) {
    int sel = clientList->GetSelection();
    if (sel != -1) {
        if (strcmp(clientList->GetString(sel).mbc_str(), "../") != 0) {
            new RenameDialog(wxT("Rename"), std::string(clientList->GetString(sel).mbc_str()), currentClientDirectory, this);
            getClientStruct(currentClientDirectory);
        }
    }
}

/*
 * When the add folder button at the server side is pressed this method will be called.
 * It will create an add folder popup.
 */
void MainFrame::addDirServer(wxCommandEvent& event) {
    new AddDirDialog(wxT("Add Folder"), currentServerDirectory, cc, this);
    getServerStruct();
}

/*
 * When the add folder button at the client side is pressed this method will be called.
 * It will create an add folder popup.
 */
void MainFrame::addDirClient(wxCommandEvent& event) {
    new AddDirDialog(wxT("Add Folder"), currentClientDirectory, this);
    getClientStruct(currentClientDirectory);
}

/*
 * When double clicked on a listitem in the clientdirectorylist this method will be called.
 * It will get the directorylist of the selected directory.
 */
void MainFrame::changeDirClient(wxCommandEvent& event) {
    int sel = clientList->GetSelection();
    if (sel != -1) {
        if (clientList->GetString(sel).GetChar(clientList->GetString(sel).size() - 1) == '/') {
            if (strcmp(clientList->GetString(sel).mbc_str(), "../") != 0) {
                std::string temp = currentClientDirectory + std::string(clientList->GetString(sel).mbc_str());
                getClientStruct(temp);
            } else {
                std::string temp = currentClientDirectory.substr(0, currentClientDirectory.size() - 1);
                int found = temp.find_last_of("/");
                getClientStruct(temp.substr(0, found + 1));
            }
        }
    }
}

/*
 * When double clicked on a listitem in the serverdirectorylist this method will be called.
 * It will get the directorylist of the selected directory.
 */
void MainFrame::changeDirServer(wxCommandEvent& event) {
    int sel = serverList->GetSelection();
    if (sel != -1) {
        if (serverList->GetString(sel).GetChar(serverList->GetString(sel).size() - 1) == '/') {
            if (strcmp(serverList->GetString(sel).mbc_str(), "../") != 0) {
                currentServerDirectory += std::string(serverList->GetString(sel).mbc_str());
                if (getServerStruct() == -1) {
                    wxMessageBox(wxT("You are not authorized to go to this directory."));
                }
            } else {
                std::string temp = "/" + currentServerDirectory.substr(0, currentServerDirectory.size() - 1);
                int found = temp.find_last_of("/");
                currentServerDirectory = temp.substr(1, found);
                if (getServerStruct() == -1) {
                    wxMessageBox(wxT("You are not authorized to go to this directory."));
                }
            }
        }
    }
}

/*
 * When called this method will clear the clientdirectorylist and refill it with the given folderpath.
 */
void MainFrame::getClientStruct(std::string folder) {
    std::vector<std::string> dirStructHome = getDirStructure(folder);
    if (dirStructHome.size() != 0) {
        currentClientDirectory = folder;
        clientList->Clear();
        //if its not the topdirectory then give the possibility to go to the parent directory
        if (currentClientDirectory != "/") {
            clientList->Append(wxT("../"));
        }
        clientDir = wxString(currentClientDirectory.c_str(), wxConvUTF8);
        clientDirText->SetLabel(clientDir);

        //fill the list with directories
        std::vector<std::string> dirsHome = cc.getDirs(dirStructHome);
        std::sort(dirsHome.begin(), dirsHome.end());
        for (unsigned int i = 0; i < dirsHome.size(); i++) {
            std::string strtemp = dirsHome.at(i) + "/";
            wxString str(strtemp.c_str(), wxConvUTF8);
            clientList->Append(str);
        }
        //fill the list with files
        std::vector<std::string> filesHome = cc.getFiles(dirStructHome);
        std::sort(filesHome.begin(), filesHome.end());
        for (unsigned int i = 0; i < filesHome.size(); i++) {
            wxString str(filesHome.at(i).c_str(), wxConvUTF8);
            clientList->Append(str);
        }
    } else {
        std::string str = "An error occurred: ";
        str += strerror(errno);
        wxMessageBox(wxString(str.c_str(), wxConvUTF8));
    }
}

/*
 * When called this method will clear the serverdirectorylist and refill it with the currentServerDirectory.
 */
int MainFrame::getServerStruct() {
    serverList->Clear();
    //if its not the topdirectory then give the possibility to go to the parent directory
    if (currentServerDirectory != "") {
        serverList->Append(wxT("../"));
    }
    std::string strtemp = "/" + currentServerDirectory;
    serverDir = wxString(strtemp.c_str(), wxConvUTF8);
    serverDirText->SetLabel(serverDir);

    std::vector<std::string> dirStruct = cc.requestDirStructure(currentServerDirectory); //TODO check errormessaging
    if (dirStruct.size() > 1) {
        std::vector<std::string> dirs = cc.getDirs(dirStruct);
        for (unsigned int i = 0; i < dirs.size(); i++) {
            std::string strtemp = dirs.at(i) + "/";
            wxString str(strtemp.c_str(), wxConvUTF8);
            serverList->Append(str);
        }
        std::vector<std::string> files = cc.getFiles(dirStruct);
        for (unsigned int i = 0; i < files.size(); i++) {
            std::string strtemp = files.at(i);
            wxString str(strtemp.c_str(), wxConvUTF8);
            serverList->Append(str);
        }
    } else {
        if (dirStruct.at(0).compare("0") == 0) {
            errorBox(0);
            exit(-1);
        }
        std::string temp = "/" + currentServerDirectory.substr(0, currentServerDirectory.size() - 1);
        int found = temp.find_last_of("/");
        currentServerDirectory = temp.substr(1, found);
        if (currentServerDirectory.compare("") != 0) {
            getServerStruct();
        }
        return -1;
    }
    return 0;
}

/*
 * When called this method will get and parse the directory structure of the server into a vector.
 */
std::vector<std::string> MainFrame::getDirStructure(std::string dirName) {
    std::vector<std::string> dirStructure;
    std::string dirstring;
    std::string filestring;

    DIR* dir;
    struct dirent *dirEntry;
    if ((dir = opendir(dirName.c_str())) == NULL) {
        Logger::getInstance().log("Could not open folder.");
        return dirStructure;
    }

    while ((dirEntry = readdir(dir)) != NULL) {
        if (dirEntry->d_name[0] != '.') {
            if (dirEntry->d_type == 4) {
                dirstring += dirEntry->d_name;
                dirstring += ",";
            } else if (dirEntry->d_type == 8) {
                filestring += dirEntry->d_name;
                filestring += ",";
            }
        }
    }
    dirStructure.push_back("0");
    dirStructure.push_back(dirstring);
    dirStructure.push_back(filestring);
    return dirStructure;
}

/*
 * When the cancel button is called this method will close the window and stop the application.
 */
void MainFrame::cancel(wxCommandEvent& event) {
    Close(TRUE);
}

/*
 * This method will create the correct error message box with the given errorcode.
 * This errorBox will check the code if its a servergiven error.
 * Errors given with "errno" should use the errorBoxClient(error) method.
 */
void MainFrame::errorBox(int code) {
    switch (code) {
        case 0:
            wxMessageBox(wxT("Server disconnected, restart of the application is necessary."));
            exit(-1);
        case ERROR_LOGIN_FAIL:
            wxMessageBox(wxT("Username or password is incorrect."));
            break;
        case ERROR_LOGIN_NOTIDENTIFIED:
            wxMessageBox(wxT("You are not logged in."));
            break;
        case ERROR_FILE_NOTPERMITTED:
            wxMessageBox(wxT("You are not permitted to do this action."));
            break;
        case ERROR_FILE_FAIL:
            wxMessageBox(wxT("You do not have the permission to do this."));
            break;
        case ERROR_FILE_ISOPEN:
            wxMessageBox(wxT("File is already open."));
            break;
        case ERROR_FILE_NOFILE:
            wxMessageBox(wxT("No file given."));
            break;
        case ERROR_FILE_EXTENTION:
            wxMessageBox(wxT("Given extension is not allowed."));
            break;
        case ERROR_FILE_SIZE:
            wxMessageBox(wxT("File is too big."));
            break;
        case ERROR_OPEN_FILE:
            wxMessageBox(wxT("You do not have the permission to do this."));
            break;
        case ERROR_WRITE_FILE:
            wxMessageBox(wxT("An error occurred while writing, the download has been aborted."));
            break;
        case ERROR_CLOSE_FILE:
            wxMessageBox(wxT("An error occurred while closing the file."));
            break;
        default:
            wxMessageBox(wxT("An unknown error occurred."));
            break;
    }
}

/*
 * This method will create an error message box with the given errno from the errno.h file.
 * Errors given from the server should be handled by the errorBox(code) method.
 */
void MainFrame::errorBoxClient(int error) {
    std::string str = "An error occurred: ";
    str += strerror(error);
    wxMessageBox(wxString(str.c_str(), wxConvUTF8));
}

void MainFrame::writeConfig() {
    int file = 0;
    if ((file = open("Configfile", O_CREAT | O_WRONLY, 0600)) == -1) {
        Logger::getInstance().log("file cannot be read");
    }
    write(file, ip->GetValue().mbc_str(), std::string(ip->GetValue().mbc_str()).size());
    write(file, "\n", 1);
    write(file, port->GetValue().mbc_str(), std::string(port->GetValue().mbc_str()).size());
    write(file, "\n", 1);
    write(file, username->GetValue().mbc_str(), std::string(username->GetValue().mbc_str()).size());
    write(file, "\n", 1);
}


